package com.vip.xchat.service.impl;

import cn.novelweb.tool.date.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vip.file.model.response.ErrorCode;
import com.vip.file.model.response.Result;
import com.vip.file.model.response.Results;
import com.vip.xchat.mapper.UserMapper;
import com.vip.xchat.mapper.XChatMapper;
import com.vip.xchat.model.Xchat;
import com.vip.xchat.model.Xuser;
import com.vip.xchat.service.IXChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class XChatServiceImpl implements IXChatService {

    @Autowired
    private XChatMapper xChatMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<Object> sendXChat(Xchat xChat) {
        xChat.setCreatedTime(DateUtils.getBaiDuTime("yyyy-MM-dd HH:mm:ss"));
        int insertSum = xChatMapper.insert(xChat);
        if (insertSum > 0) {
            xChat.setMe(true);
            return Results.newSuccessResult(xChat, "信息发送成功!");
        }
        return Results.newFailResult(ErrorCode.SYSTEM_ERROR, "请求出现问题!");
    }

    @Override
    public Result<Object> selectXChatList(Integer pageNo, Integer pageSize,String userId,String sessionId) {
        try {
            pageNo = StringUtils.isEmpty(pageNo) ? 1 : pageNo;
            pageSize = StringUtils.isEmpty(pageSize) ? 15 : pageSize;
            Page<Xchat> page = new Page(pageNo,pageSize);
            //queryWrapper组装查询where条件
            LambdaQueryWrapper<Xchat> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!StringUtils.isEmpty(sessionId),Xchat::getSessionId,sessionId)
               .orderByDesc(Xchat::getCreatedTime);
            Page<Xchat> xchatPage = xChatMapper.selectPage(page, queryWrapper);
            List<Xchat> records = xchatPage.getRecords();
            for (Xchat xchat : records) {
                String sendUserId = xchat.getUserId();
                Xuser xuser = userMapper.selectById(sendUserId);
                if (!StringUtils.isEmpty(xchat))
                    xchat.setUserCover(xuser.getCover());
                if (userId.equals(sendUserId))
                    xchat.setMe(true);
            }
            Collections.reverse(records);
            return Results.newSuccessResult(xchatPage, "查询成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Results.newFailResult(ErrorCode.DB_ERROR, "查询失败!");
    }

}
